package com.liuscraft.tradingplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuscraft.tradingplatform.entity.LuckPermission;
import com.liuscraft.tradingplatform.entity.LuckRolePermission;
import com.liuscraft.tradingplatform.mapper.LuckRolePermissionMapper;
import com.liuscraft.tradingplatform.service.ILuckPermissionService;
import com.liuscraft.tradingplatform.service.ILuckRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiusCraft
 * @since 2023-03-06
 */
@Service
public class LuckRolePermissionServiceImpl extends ServiceImpl<LuckRolePermissionMapper, LuckRolePermission> implements ILuckRolePermissionService {
    @Resource
    ILuckPermissionService luckPermissionService;

    @Override
    public LuckRolePermission addPermissionToRole(Integer permissionId, Integer roleId) {
        LuckRolePermission luckRolePermission = new LuckRolePermission();
        luckRolePermission.setPermissionId(permissionId);
        luckRolePermission.setRoleId(roleId);
        getBaseMapper().insert(luckRolePermission);
        return luckRolePermission;
    }

    @Override
    public List<LuckPermission> getRolesPermission(Set<Integer> roleIds) {
        LambdaQueryWrapper<LuckRolePermission> lambdaQuery = new LambdaQueryWrapper<>();
        roleIds.forEach(v->{
            lambdaQuery.or().eq(LuckRolePermission::getRoleId, v);
        });
        Set<Integer> permissionIds = list(lambdaQuery)
                .stream()
                .map(LuckRolePermission::getPermissionId)
                .collect(Collectors.toSet());
        return new ArrayList<>(luckPermissionService.listByIds(permissionIds));
    }

    @Override
    public List<LuckPermission> getRolePermission(Integer roleId) {
        LambdaQueryWrapper<LuckRolePermission> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(LuckRolePermission::getRoleId, roleId);
        Set<Integer> list = list(lambdaQuery).stream().map(LuckRolePermission::getPermissionId).collect(Collectors.toSet());
        if (ObjectUtils.isEmpty(list)) return new ArrayList<>();
        return (List<LuckPermission>) luckPermissionService.listByIds(list);
    }
}
